package com.ivr.cm.http;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.ivr.cm.util.SpringServiceUtil;
/**
 * 通过URL调用的方式来重新加载，目前只支持同步加载方式
 * @author liugeng
 * @date 2015-12-18
 *
 */
public class ReloadController implements Controller {
	private static Logger logger = Logger.getLogger(ReloadController.class);

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		String bean = request.getParameter("bean");
		if(bean == null){
			logger.info("不合法的参数");
			return null;
		}
		
		Runnable run = null;
		try{
			run = (Runnable) SpringServiceUtil.getService(bean);
			run.run();
		}catch (Exception e) {
			logger.error(String.format("[%s]加载缓存异常%s", bean,ExceptionUtils.getFullStackTrace(e)));
			output(response,String.format("[%s]加载缓存异常%s", bean,ExceptionUtils.getFullStackTrace(e)));
		}
		output(response,bean + "重新加载完成");
		return null;
	}
	
	private void output(HttpServletResponse response,String message) throws IOException{
		OutputStream os = response.getOutputStream();
		os.write(message.getBytes());
		os.flush();
		os.close();
	}

}